

let templateDiv = `
 <div>
            <label>工具</label>
            <div>
                <button id="btn_add_chain">添加一条轨道</button>
            </div>
            <div>
                <button id="btn_show_chain_quad">显示实心轨道</button>
            </div>
            <div>
                <button id="btn_show_chain_line">显示线型轨道</button>
            </div>
            <div>
                <button id="btn_clean_map">清空地图</button>
            </div>
            <div>
                <button id="btn_del_chain">删除当前轨道</button>
            </div>
            <div>
                <button id="btn_del_selnode">删除当前节点</button>
            </div>
            <div>
                <button id="btn_output_img">导出轨道图片</button>
            </div>
                
            <!--<div>-->
                <!--<button id="btn_ball_roll">球进行滚动</button>-->
            <!--</div>-->
</div>`;

let BaseView = require('../BaseView');
let settings = require('../../settings');
let Resize = require('../../utils/resize');
let fastPng = require('fast-png');

let RemoveSelCommand = require('../../cmds/rmSelCmd');
let RemoveChainCommand = require('../../cmds/removeChainCmd');
let AddChainCommand = require('../../cmds/addChainCmd');

class ToolView extends BaseView {

    constructor() {
        super();

        this.rootEl = document.createElement('div');
        this.rootEl.classList.add('border');
        this.rootEl.innerHTML = templateDiv;

        // 添加一条轨道
        let btnAddChain = this.rootEl.querySelector('#btn_add_chain');
        btnAddChain.addEventListener('click',()=>{
            if(editor.isEditChainState()){
                let mapScene = editor.gameApp;
                if (mapScene.lstChain.length > 1) {
                    settings.alert('最多支持两条路径!');
                    return;
                }
                let addChainCmd = new AddChainCommand();
                editor.execute(addChainCmd);
            }else{
                settings.alert('请切换到轨道编辑模式');
            }
        },false);

        // 显示实心轨道
        let btnShowQuadChain = this.rootEl.querySelector('#btn_show_chain_quad');
        btnShowQuadChain.addEventListener('click',()=>{
            let mapScene = editor.gameApp;
            mapScene.setChainType(G.ChainDrawMode.Quad);
        },false);

        // 显示线型轨道
        let btnShowLineChain = this.rootEl.querySelector('#btn_show_chain_line');
        btnShowLineChain.addEventListener('click',()=>{
            let mapScene = editor.gameApp;
            mapScene.setChainType(G.ChainDrawMode.Line);
        },false);

        // 清空地图
        let btnClean = this.rootEl.querySelector('#btn_clean_map');
        btnClean.addEventListener('click',()=>{
            if(settings.showConfirmDialog('清空地图后不可恢复,确定要清空地图么?')){
                editor.cleanAllMap();
            }
        },false);

        // 删除当前轨道
        let btnDeleteChain = this.rootEl.querySelector('#btn_del_chain');
        btnDeleteChain.addEventListener('click',()=>{
            if(editor.isEditChainState()){
                if(settings.showConfirmDialog('确定要删除此条轨道么?')){
                    let mapScene = editor.gameApp;
                    let removeChainCmd = new RemoveChainCommand(mapScene.curChain);
                    editor.execute(removeChainCmd);
                }
            }else{
                settings.alert('请切换到轨道编辑模式');
            }
        },false);

        // 删除当前节点
        let btnDeleteNode = this.rootEl.querySelector('#btn_del_selnode');
        btnDeleteNode.addEventListener('click',this._onDelSelNode.bind(this),false);

        // 导出轨道图片
        let btnExportImg = this.rootEl.querySelector('#btn_output_img');
        btnExportImg.addEventListener('click',this._onExportChainImg.bind(this),false);

        // 模拟一个球进行滚动
        // let btnBallRoll = this.rootEl.querySelector('#btn_ball_roll');
        // btnBallRoll.addEventListener('click',()=>{
        //
        // },false);
    }

    _onDelSelNode(){
        let mapScene = editor.gameApp;

        if(!editor.isEditChainState()){
            settings.alert('请先切换到轨道编辑模式');
            return;
        }

        let curSel = mapScene.curSel;
        if(!curSel){
            settings.alert('请先选中要删除的节点.');
            return;
        }

        if(!settings.showConfirmDialog('确定要删除此节点么?')){
            return;
        }


        let cmd = new RemoveSelCommand(mapScene.curChain,curSel);
        editor.execute(cmd);

        // 删除的不是最后一个sel, 所以还需要记录 sel 的位置
        // 恢复的时候,将sel插入到相应的位置

    }

    _onExportChainImg(){

        let filepath = settings.getSaveFilePath('png');
        if(filepath){
            console.log('准备截图并且存在:',filepath);

            let mainCamera = cc.Camera.main;

            // 新建一个 RenderTexture，并且设置 camera 的 targetTexture 为新建的 RenderTexture，这样 camera 的内容将会渲染到新建的 RenderTexture 中。
            let gl = cc.game._renderContext;

            // let mapScene = editor.gameApp;
            // let x = ~~mapScene.offsetX/2;
            // let y = ~~mapScene.offsetY/2;
            let x = 60;
            let y = 80;
            let width = 360;
            let height = 640;
            let format = gl.RGBA;
            let type = gl.UNSIGNED_BYTE;
            let pixel = new Uint8Array(width * height * 4);

            mainCamera.render(cc.director.getScene());
            // mapScene.renderScene();

            gl.readPixels(x,y,width,height,format,type,pixel);

            pixel = this._flipPixels(width,height,pixel);

            // 需要返回一个 720x1280 的图片
            let retW = 720;
            let retH = 1280;
            try{
                let resize = new Resize(width,height,retW,retH,true,true,function (buffer) {
                    let buf = fastPng.encode({width:retW,height:retH,data:buffer});
                    window.fs.writeFileSync(filepath,buf);
                    settings.alert('存储成功!');
                });
                resize.resize(pixel);
            }catch (e) {
                settings.alert('存储出现错误. e:' + e.toString());
            }
        }

        ////


        // let filepath = settings.getSaveFilePath('png');
        // if(filepath){
        //     console.log('准备截图并且存在:',filepath);
        //     let gl = dd.cfg.gl;
        //
        //     let mapScene = editor.gameApp.getCurScene();
        //     let x = ~~mapScene.offsetX/2;
        //     let y = ~~mapScene.offsetY/2;
        //     let width = 360;
        //     let height = 640;
        //     let format = gl.RGBA;
        //     let type = gl.UNSIGNED_BYTE;
        //     let pixel = new Uint8Array(width * height * 4);
        //
        //     mapScene.renderScene();
        //
        //     gl.readPixels(x,y,width,height,format,type,pixel);
        //
        //     pixel = this._flipPixels(width,height,pixel);
        //
        //     // 需要返回一个 720x1280 的图片
        //     let retW = 720;
        //     let retH = 1280;
        //     try{
        //         let resize = new Resize(width,height,retW,retH,true,true,function (buffer) {
        //             let buf = fastPng.encode({width:retW,height:retH,data:buffer});
        //             window.fs.writeFileSync(filepath,buf);
        //             settings.alert('存储成功!');
        //         });
        //         resize.resize(pixel);
        //     }catch (e) {
        //         settings.alert('存储出现错误. e:' + e.toString());
        //     }
        // }
    }

    _flipPixels(width,height,pixels){
        let newPixels = new Uint8Array(width * height * 4);
        for(let i = 0; i < height;++i){
            for(let j = 0; j < width; ++j){
                let dst =  4 * width * i + j * 4;
                let src = 4 * width * (height - i - 1) + j * 4;
                newPixels[dst] = pixels[src];
                newPixels[dst+1] = pixels[src+1];
                newPixels[dst+2] = pixels[src+2];
                newPixels[dst+3] = pixels[src+3];
            }
        }
        return newPixels;
    }
}

module.exports = ToolView;
